package com.findMe.controller;

import com.findMe.entity.OneJacksonEntity;
import com.findMe.entity.User;
import com.findMe.exception.UserException;
import com.findMe.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping(path = "user")
public class UserController {

    @Autowired
    @Qualifier("UserService")
    private UserService userService;

    @PostMapping(path = "regist")
    public @ResponseBody OneJacksonEntity regist(User user){
        OneJacksonEntity oneJacksonEntity = new OneJacksonEntity();
        try {
            User regist = userService.regist(user);

            oneJacksonEntity.setMsg("请求成功");
            oneJacksonEntity.setData(regist);
            oneJacksonEntity.setStatus(200);
        } catch (UserException e) {
            oneJacksonEntity.setStatus(201);
            oneJacksonEntity.setMsg(e.getMessage());
        }

        return oneJacksonEntity;
    }

    @PostMapping(path = "login")
    public @ResponseBody OneJacksonEntity login(User user, HttpServletRequest request){
        OneJacksonEntity oneJacksonEntity = new OneJacksonEntity();

        try {
            User login = userService.login(user);

            request.getSession().setAttribute("user",login);

            oneJacksonEntity.setMsg("请求成功");
            oneJacksonEntity.setData(login);
            oneJacksonEntity.setStatus(200);
        } catch (UserException e) {
            oneJacksonEntity.setStatus(201);
            oneJacksonEntity.setMsg(e.getMessage());
        }

        return oneJacksonEntity;
    }

}
